package com.woniu.order.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.exception.file.FileException;
import com.woniu.model.Result;
import com.woniu.order.form.*;
import com.woniu.order.model.TOrder;
import com.woniu.order.param.*;
import com.woniu.order.service.TOrderService;
import com.woniu.order.util.*;
import com.woniu.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年05月23日
 */
@RestController
@RequestMapping("/tOrder")
@Api(tags = "订单服务接口")
public class TOrderController {
    @Resource
    private TOrderService orderService;

    @Resource
    private RedisUtil redisUtil;


    @Resource
    private AlipayUtil alipayUtil;

    @Resource
    private Alpay alpay;


    /**
     * 新增预约上门收废品
     * @param form 新增预约对象
     * @return
     */
    @ApiOperation("新增预约上门收废品")
    @PostMapping("/bookingOrder")
    public Result<TOrder> bookingOrder(@RequestBody AddBookingOrderForm form,@RequestHeader("token") String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        //获取token
        Integer  userId = Integer.parseInt(JwtUtil.parseToken(refreshToken, JwtUtil.userSecret).get("accountId").toString());

        TOrder tOrder = orderService.insetOrder(userId,BeanUtil.toBean(form, AddBookingOrderParam.class));
        return Result.newInstance(TOrder.class).setData(tOrder).setMessage("预约成功");
    }
    /**
     * 新增预约上门收废品返回的押金form为空
     * @param form 新增预约对象
     * @return
     */
    @ApiOperation("新增预约上门收废品返回的押金form为空")
    @PostMapping("/bookingOrders")
    public Result<TOrder> bookingOrders(@RequestBody AddBookingOrdersForm form,@RequestHeader("token") String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        //获取token
        Integer  userId = Integer.parseInt(JwtUtil.parseToken(refreshToken, JwtUtil.userSecret).get("accountId").toString());

        TOrder tOrder = orderService.insetOrders(userId,BeanUtil.toBean(form, AddBookingOrdersparam.class));
        return Result.newInstance(TOrder.class).setData(tOrder).setMessage("预约成功");
    }

    /**
     * 上传图片
     */
    @ApiOperation("员工上传图片")
    @PostMapping("/uploadImage")
    public Result<String> uploadPhoto(MultipartFile image,@RequestHeader("token") String token) throws Exception {
        System.out.println(token);
        String refreshToken = redisUtil.get(token);
        JwtUtil.parseEmployToken(refreshToken);

        if (!FileUtil.isImageFile(image.getInputStream())){
            throw  new FileException(9999,"文件类型错误");
        }
        String oldName = image.getOriginalFilename();
        String suffix = oldName.substring(oldName.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString();

        String filePath = OSSUtilJin.uploadFile(image.getInputStream(),   fileName+suffix, "jinaisen");
        System.out.println(filePath);
        return Result.newInstance(String.class).setData(filePath).setMessage("上传图片成功");
    }

    /**
     * 站点分配员工
     * @param form 订单编号 员工id
     * @return 返回订单
     */
    @ApiOperation("站点分配员工")
    @PostMapping("/assignmentEmployee")
    public Result<TOrder> assignmentEmployee(@RequestBody AssignmentEmployeeForm form,@RequestHeader String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        JwtUtil.parseStationBossToken(refreshToken);
        System.out.println("拿到的员工id: "+form.getEmployeeId());
        TOrder t = orderService.assignmentEmployee(BeanUtil.toBean(form, AssignmentEmployeeParam.class));
        return Result.newInstance(TOrder.class).setData(t).setMessage("分配成功");
    }

//    /**
//     * 员工出发
//     * @param orderNum 订单编号
//     * @param token
//     * @return
//     */
//    @ApiOperation("员工出发")
//    @PostMapping("/employeeGo/{orderNum}")
//    public Result<TOrder> employeeGo(
//            @ApiParam(name = "orderNum",value = "订单编号")
//            @PathVariable("orderNum")
//            String orderNum,
//            @RequestHeader("token")
//            String token) throws Exception {
//
//        String refreshToken = redisUtil.get(token);
//        Integer userId = Integer.parseInt(JwtUtil.parseToken(refreshToken,JwtUtil.employSecret).get("accountId").toString());
//        TOrder tOrder = orderService.employeeGo(orderNum,userId);
//        return Result.newInstance(TOrder.class).setData(tOrder).setMessage("成功出发");
//    }


    /**
     * 商家转账测试
     * @return
     */
    @ApiOperation("商家无密转账")
    @PostMapping("/translationPay/{orderNum}")
    public Result translationPay(
            @ApiParam(name = "orderNum",value = "订单编号")
            @PathVariable("orderNum")
            String orderNum,
            @RequestHeader("token")
            String token
    ) throws Exception {
        String refreshToken = redisUtil.get(token);
        Integer userId = Integer.parseInt(JwtUtil.parseToken(refreshToken,JwtUtil.stationBossSecret).get("accountId").toString());
        TOrder s = orderService.translationPay(userId,orderNum);
        return Result.newInstance(TOrder.class).setData(s).setMessage("商家向用户转帐成功");
    }

    /**
     * 用户确认订单
     * @param orderNum 订单编号
     * @param token
     * @return
     */
    @ApiOperation("用户确认订单")
    @GetMapping("/userQueryOrder/{orderNum}")
    public Result userQueryOrder(
            @ApiParam(name = "orderNum",value = "订单编号")
            @PathVariable("orderNum")
            String orderNum,@RequestHeader("token") String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        Integer userId = Integer.parseInt(JwtUtil.parseToken(refreshToken,JwtUtil.userSecret).get("accountId").toString());

        TOrder tOrder = orderService.userQueryOrder(userId,orderNum);
        return Result.newInstance(TOrder.class).setData(tOrder).setMessage("用户操作成功");
    }

    /**
     * 用户取消订单
     * @param orderNum 订单编号
     * @param token
     * @return
     */
    @ApiOperation("用户取消订单")
    @GetMapping("/cancelOrder/{orderNum}")
    public Result cancelOrder(
            @ApiParam(name = "orderNum",value = "订单编号")
            @PathVariable("orderNum")
            String orderNum,@RequestHeader("token") String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        Integer userId = Integer.parseInt(JwtUtil.parseToken(refreshToken,JwtUtil.userSecret).get("id").toString());
        Integer accountId = Integer.parseInt(JwtUtil.parseToken(refreshToken,JwtUtil.userSecret).get("accountId").toString());

        TOrder tOrder = orderService.cancelOrder(userId,accountId,orderNum);
        return Result.newInstance(TOrder.class).setData(tOrder).setMessage("用户操作成功");
    }

    /**
     * 用户拒绝订单
     * @param orderNum 订单编号
     * @param token
     * @return
     */
    @ApiOperation("用户拒绝订单")
    @GetMapping("/refuseOrder/{orderNum}")
    public Result refuseOrder(
            @ApiParam(name = "orderNum",value = "订单编号")
            @PathVariable("orderNum")
            String orderNum,
            @RequestHeader("token")
            String token
    ) throws Exception {
        String refreshToken = redisUtil.get(token);
        Integer userId = Integer.parseInt(JwtUtil.parseToken(refreshToken,JwtUtil.userSecret).get("accountId").toString());

        TOrder tOrder = orderService.refuseOrder(userId,orderNum);
        return Result.newInstance(TOrder.class).setData(tOrder).setMessage("用户操作成功");
    }

//    /**
//     * 站点通过
//     * @param orderNum 订单编号
//     * @param token
//     * @return
//     */
//    @ApiOperation("站点通过")
//    @GetMapping("/siteQuery/{orderNum}")
//    public Result siteQuery(
//            @ApiParam(name = "orderNum",value = "订单编号")
//            @PathVariable("orderNum")
//            String orderNum,
//            @RequestHeader("token")
//            String token
//    ) throws Exception {
//        String refreshToken = redisUtil.get(token);
//        Integer userId = Integer.parseInt(JwtUtil.parseToken(refreshToken,JwtUtil.stationBossSecret).get("accountId").toString());
//
//        TOrder tOrder = orderService.siteQuery(userId,orderNum);
//        return Result.newInstance(TOrder.class).setData(tOrder).setMessage("用户操作成功");
//    }

    /**
     * 站点拒绝通过
     * @param orderNum 订单编号
     * @param token
     * @return
     */
    @ApiOperation("站点拒绝通过")
    @GetMapping("/refuseQuery/{orderNum}")
    public Result refuseQuery(
            @ApiParam(name = "orderNum",value = "订单编号")
            @PathVariable("orderNum")
            String orderNum,
            @RequestHeader("token")
            String token
    ) throws Exception {
        String refreshToken = redisUtil.get(token);
        Integer userId = Integer.parseInt(JwtUtil.parseToken(refreshToken,JwtUtil.stationBossSecret).get("accountId").toString());

        TOrder tOrder = orderService.refuseQuery(userId,orderNum);
        return Result.newInstance(TOrder.class).setData(tOrder).setMessage("站点通过");
    }

//    /**
//     *员工返程
//     * @param orderNum 订单编号
//     * @param token
//     * @return
//     */
//    @ApiOperation("员工返程")
//    @GetMapping("/employeeBack/{orderNum}")
//    public Result employeeBack(
//            @PathVariable("orderNum")
//            @ApiParam(name = "orderNum",value = "订单编号")
//            String orderNum,
//            @RequestHeader("token")
//            String token) throws Exception {
//        String refreshToken = redisUtil.get(token);
//        Integer userId = Integer.parseInt(JwtUtil.parseToken(refreshToken,JwtUtil.employSecret).get("accountId").toString());
//        TOrder tOrder = orderService.employeeBack(userId,orderNum);
//        return Result.newInstance(TOrder.class).setData(tOrder).setMessage("员工已到达站点");
//    }

    /**
     * 根据状态分页查询员工订单
     * @param form 状态码 页码 每页个数
     * @return 订单page对象
     */
    @PostMapping("/findStateOrder")
    public Result findStateOrder(@RequestBody FindStateOrderForm form, @RequestHeader String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        Integer userId = Integer.parseInt(JwtUtil.parseToken(refreshToken,JwtUtil.employSecret).get("accountId").toString());
        System.out.println(JSONUtil.toJsonStr(form));
        Page<TOrder> tOrder = orderService.findStateOrder(userId,BeanUtil.toBean(form, FindStateOrderParam.class));
        return Result.newInstance(Page.class).setData(tOrder).setMessage("根据状态查询成功");
    }

    /**
     * 根据站点id查询该站点所属所有订单
     * id 站点id
     */
    @GetMapping("/findByStationId")
    @ApiOperation("根据站点id查询该站点所属所有订单")
    public Result<Page<TOrder>> findByStationId(@RequestParam("id") Integer id,@RequestParam("pageNum") Integer pageNum,@RequestParam("pageSize") Integer pageSize,@RequestHeader String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        JwtUtil.parseStationBossToken(refreshToken);
        Page<TOrder> pages = orderService.findByStationId(id,pageNum,pageSize);
        return Result.newPageInstance(TOrder.class).setCode(200).setData(pages).setMessage("根据站点id查询该站点所属所有订单成功!");
    }


    /**
     * 根据站点id查询该站点所有待站点审批订单
     * id 站点id
     */
    @GetMapping("/findUnHandelByStationId")
    @ApiOperation("根据站点id查询该站点所属所有订单")
    public Result<Page<TOrder>> findUnHandelByStationId(@RequestParam("id") Integer id,@RequestParam("pageNum") Integer pageNum,@RequestParam("pageSize") Integer pageSize,@RequestHeader String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        JwtUtil.parseStationBossToken(refreshToken);
        Page<TOrder> pages = orderService.findUnHandelByStationId(id,pageNum,pageSize);
        return Result.newPageInstance(TOrder.class).setCode(200).setData(pages).setMessage("根据站点id查询该站点所属所有订单成功!");
    }

    /**
     * 根据站点id查询该站点所有待分配员工订单
     * id 站点id
     */
    @GetMapping("/findUnAssByStationId")
    @ApiOperation("根据站点id查询该站点所属所有订单")
    public Result<Page<TOrder>> findUnAssByStationId(@RequestParam("id") Integer id,@RequestParam("pageNum") Integer pageNum,@RequestParam("pageSize") Integer pageSize,@RequestHeader String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        JwtUtil.parseStationBossToken(refreshToken);
        Page<TOrder> pages = orderService.findUnAssByStationId(id,pageNum,pageSize);
        return Result.newPageInstance(TOrder.class).setCode(200).setData(pages).setMessage("根据站点id查询待分配员工订单成功!");
    }

    @GetMapping("/findById/{id}")
    @ApiOperation("根据订单id查询订单")
    public Result<TOrder> findById(@PathVariable("id") String id){
        return Result.newInstance(TOrder.class).setCode(200).setData(orderService.getById(id)).setMessage("根据订单id查询订单成功!");
    }


    /**
     * 根据账号id返回订单集合
     * @param id 账号id
     * @return
     */
    @ApiOperation("根据账号id返回订单集合")
    @GetMapping("/findMyOrders/{id}")
    Result<List<TOrder>> findOrderByAccountId(@PathVariable("id")Integer id){
        List<TOrder> list =  orderService.findOrderByAccountId(id);
        return Result.newListInstance(TOrder.class).setCode(200).setData(list).setMessage("根据账号id返回订单集合成功!");
    }

}

